using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class DataManager
{
    private const string GameCountKey = "GameCount";
    private const string LastScoreKey = "LastScore";
    private const string LeaderboardKey = "Leaderboard";

    public static int GameCount
    {
        get => PlayerPrefs.GetInt(GameCountKey, 0);
        set => PlayerPrefs.SetInt(GameCountKey, value);
    }

    public static float LastScore
    {
        get => PlayerPrefs.GetFloat(LastScoreKey, 0);
        set => PlayerPrefs.SetFloat(LastScoreKey, value);
    }

    public static List<float> Leaderboard
    {
        get
        {
            string json = PlayerPrefs.GetString(LeaderboardKey, "");
            if (string.IsNullOrEmpty(json)) return new List<float>();
            return JsonUtility.FromJson<LeaderboardData>(json).scores;
        }
        set
        {
            LeaderboardData data = new LeaderboardData { scores = value };
            PlayerPrefs.SetString(LeaderboardKey, JsonUtility.ToJson(data));
        }
    }

    public static void AddToLeaderboard(float time)
    {
        var list = Leaderboard;
        list.Add(time);
        list.Sort((a, b) => a.CompareTo(b));
        if (list.Count > 10) list.RemoveAt(10);
        Leaderboard = list;
    }

    [System.Serializable]
    private class LeaderboardData
    {
        public List<float> scores = new List<float>();
    }
}
